import express from 'express'
import { executeQuery } from '../config/database.js'
import { authenticateToken } from '../middleware/auth.js'

const router = express.Router()

// 获取所有考勤设置
router.get('/attendance', authenticateToken, async (req, res) => {
  try {
    const settings = await executeQuery(
      'SELECT setting_name, setting_value, description FROM attendance_settings ORDER BY setting_name'
    )
    
    // 转换为更友好的格式
    const settingsMap = {}
    settings.forEach(setting => {
      settingsMap[setting.setting_name] = {
        value: setting.setting_value,
        description: setting.description
      }
    })
    
    res.json({
      success: true,
      data: settingsMap
    })
  } catch (error) {
    console.error('获取考勤设置失败:', error)
    res.status(500).json({
      success: false,
      message: '获取考勤设置失败'
    })
  }
})

// 更新考勤设置
router.put('/attendance', authenticateToken, async (req, res) => {
  try {
    const { role } = req.user
    
    // 只有管理员可以修改设置
    if (role !== 'admin') {
      return res.status(403).json({
        success: false,
        message: '权限不足，只有管理员可以修改考勤设置'
      })
    }
    
    const { arrival_time, departure_time, modification_limit_time } = req.body
    
    // 验证时间格式 (HH:MM:SS)
    const timeRegex = /^([01]?[0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]$/
    
    if (arrival_time && !timeRegex.test(arrival_time)) {
      return res.status(400).json({
        success: false,
        message: '入园时间格式不正确，请使用 HH:MM:SS 格式'
      })
    }
    
    if (departure_time && !timeRegex.test(departure_time)) {
      return res.status(400).json({
        success: false,
        message: '离园时间格式不正确，请使用 HH:MM:SS 格式'
      })
    }
    
    if (modification_limit_time && !timeRegex.test(modification_limit_time)) {
      return res.status(400).json({
        success: false,
        message: '限制标记时间格式不正确，请使用 HH:MM:SS 格式'
      })
    }
    
    // 更新设置
    const updates = []
    if (arrival_time) {
      await executeQuery(
        'UPDATE attendance_settings SET setting_value = ? WHERE setting_name = ?',
        [arrival_time, 'arrival_time']
      )
      updates.push('入园时间')
    }
    
    if (departure_time) {
      await executeQuery(
        'UPDATE attendance_settings SET setting_value = ? WHERE setting_name = ?',
        [departure_time, 'departure_time']
      )
      updates.push('离园时间')
    }
    
    if (modification_limit_time) {
      await executeQuery(
        'UPDATE attendance_settings SET setting_value = ? WHERE setting_name = ?',
        [modification_limit_time, 'modification_limit_time']
      )
      updates.push('限制标记时间')
    }
    
    if (updates.length === 0) {
      return res.status(400).json({
        success: false,
        message: '没有提供要更新的设置'
      })
    }
    
    res.json({
      success: true,
      message: `${updates.join('、')}更新成功`
    })
    
  } catch (error) {
    console.error('更新考勤设置失败:', error)
    res.status(500).json({
      success: false,
      message: '更新考勤设置失败'
    })
  }
})

// 获取单个设置值（用于内部调用）
router.get('/attendance/:settingName', async (req, res) => {
  try {
    const { settingName } = req.params
    
    const [setting] = await executeQuery(
      'SELECT setting_value FROM attendance_settings WHERE setting_name = ?',
      [settingName]
    )
    
    if (!setting) {
      return res.status(404).json({
        success: false,
        message: '设置不存在'
      })
    }
    
    res.json({
      success: true,
      data: setting.setting_value
    })
    
  } catch (error) {
    console.error('获取设置失败:', error)
    res.status(500).json({
      success: false,
      message: '获取设置失败'
    })
  }
})

// 为所有学生生成当日考勤记录
router.post('/generate-daily-records', authenticateToken, async (req, res) => {
  try {
    const { role } = req.user
    
    // 只有管理员可以生成记录
    if (role !== 'admin') {
      return res.status(403).json({
        success: false,
        message: '权限不足，只有管理员可以生成考勤记录'
      })
    }
    
    const today = new Date().toISOString().split('T')[0]
    
    // 检查今日是否已有记录
    const existingRecords = await executeQuery(
      'SELECT COUNT(*) as count FROM attendance_records WHERE attendance_date = ?',
      [today]
    )
    
    if (existingRecords[0].count > 0) {
      return res.status(400).json({
        success: false,
        message: `今日(${today})已存在考勤记录，无需重复生成`
      })
    }
    
    // 获取所有学生
    const students = await executeQuery(
      'SELECT id FROM students'
    )
    
    if (students.length === 0) {
      return res.status(400).json({
        success: false,
        message: '没有找到学生数据'
      })
    }
    
    // 批量插入考勤记录
    const insertPromises = students.map(student => 
      executeQuery(
        `INSERT INTO attendance_records 
         (student_id, attendance_date, arrival_status, departure_status) 
         VALUES (?, ?, 'absent', 'not_left')`,
        [student.id, today]
      )
    )
    
    await Promise.all(insertPromises)
    
    res.json({
      success: true,
      message: `成功为${students.length}名学生生成${today}的考勤记录`,
      data: {
        date: today,
        studentCount: students.length
      }
    })
    
  } catch (error) {
    console.error('生成考勤记录失败:', error)
    res.status(500).json({
      success: false,
      message: '生成考勤记录失败'
    })
  }
})

export default router